/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package foxmob.mlts.view.marker;

import foxmob.mlts.controller.marker.MarkAnswerFormController;
import foxmob.mlts.interfaces.marker.AssessmentPanelDelegate;
import foxmob.mlts.model.Question;
import foxmob.mlts.viewcontroller.marker.MarkAnswerForm;
import foxmob.mlts.viewcontroller.setter.QuestionForm;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import javax.swing.JEditorPane;
import javax.swing.text.BadLocationException;
import javax.swing.text.Element;
import javax.swing.text.StyleConstants;
import javax.swing.text.html.HTML;
import javax.swing.text.html.HTMLDocument;

/**
 *
 * @author Lunayo
 */
public class MarkAnswerDetailPanel extends javax.swing.JPanel implements AssessmentPanelDelegate{

    /**
     * Creates new form MarkAnswerDetailPanel
     */
    public MarkAnswerDetailPanel() {
        initComponents();
        questionEditorPanel.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"));
    }
    
    public void setQuestion(Question question) {
        this.question = question;
    }
    
    public void setDelegate(MarkAnswerFormController delegate) {
        this.delegate = delegate;
    }
    
    public void setQuestionText(String questionText) {
        // reset the document
        questionEditorPanel.setEditorKit(JEditorPane.createEditorKitForContentType("text/html"));
        HTMLDocument doc = (HTMLDocument)questionEditorPanel.getDocument();
        // find matching pattern 
        if (studentAnswer != null) {
            String stringPattern = "_______";
            String numberPattern = "(?!<b>)(\\([0-9]\\))(?!</b>)";
            Pattern pattern = Pattern.compile(numberPattern);
            Matcher matcher = pattern.matcher(questionText);
            int count = 1;
            // replace bold answer
            count = 1;
            while (matcher.find()) {
                String boldNumber = "<b>(" + count + ")</b>";
                questionText =
                            questionText.replaceFirst(numberPattern, boldNumber);
                if (studentAnswer.length >= count) {
                    String boldAnswer = "<b>" + this.studentAnswer[count - 1] + "</b>";
                    
                    questionText =
                            questionText.replaceFirst(stringPattern, boldAnswer);
                }
                ++count;
            }
        }
        Element paragraph =
            doc.getElement(doc.getDefaultRootElement(), StyleConstants.NameAttribute, HTML.Tag.P);
        try {
            doc.insertBeforeEnd(paragraph, questionText);
        } catch (BadLocationException ex) {
            Logger.getLogger(QuestionForm.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex) {
            Logger.getLogger(QuestionForm.class.getName()).log(Level.SEVERE, null, ex);
        }
        questionEditorPanel.setDocument(doc);
    }
    
    public void setAssesmentBlank(boolean[] assessmentBlank) {
        if (assessmentBlank == null) return;
        int i = 0;
        for (boolean isCorrect : assessmentBlank) {
            AssessmentPanel markPanel =
                    (AssessmentPanel)this.assesmentPanel.getComponent(i);
            markPanel.setIsCorrect(isCorrect);
            ++i;
        }
    }
    
    public void setAssessmentBlankPanel(int number) {
        this.assesmentPanel.removeAll();
        for (int i = 1; i <= number; ++i) {
            AssessmentPanel markPanel = new AssessmentPanel();
            markPanel.setDelegate(this);
            markPanel.setNumberLabel(i);
            this.assesmentPanel.add(markPanel);
        }
        try {
            delegate.setAssessmentBlankPanelDidFinish();
        } catch (Exception e) {
            System.err.print("Error : Method was not found. " + e.getMessage());
        }
    }
    
    public void setStudentAnswer(String[] studentAnswer) {
        this.studentAnswer = studentAnswer;
    }
    
    /**
     * Notification
     * 
     */
    
    @Override
    public void wrongRadioButtonDidTap(int number) {
        try {
            delegate.assessmentWrongRadioButtonDidTap(number, question);
        } catch (Exception e) {
            System.err.print("Error : Method was not found. " + e.getMessage());
        }
    }

    @Override
    public void correctRadioButtonDidTap(int number) {
        try {
            delegate.assessmentCorrectRadioButtonDidTap(number, question);
        } catch (Exception e) {
            System.err.print("Error : Method was not found. " + e.getMessage());
        }
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        mainPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        questionEditorPanel = new javax.swing.JEditorPane();
        questionLabel = new javax.swing.JLabel();
        assesmentPanel = new javax.swing.JPanel();
        jLabel1 = new javax.swing.JLabel();
        saveButton = new javax.swing.JButton();

        mainPanel.setBorder(javax.swing.BorderFactory.createTitledBorder("Mark Answer"));

        questionEditorPanel.setEditable(false);
        questionEditorPanel.setPreferredSize(new java.awt.Dimension(250, 16));
        jScrollPane1.setViewportView(questionEditorPanel);

        questionLabel.setText("Question :");

        assesmentPanel.setLayout(new javax.swing.BoxLayout(assesmentPanel, javax.swing.BoxLayout.Y_AXIS));

        jLabel1.setText("Assesment :");

        saveButton.setText("Save");
        saveButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveButtonActionPerformed(evt);
            }
        });

        org.jdesktop.layout.GroupLayout mainPanelLayout = new org.jdesktop.layout.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
            mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(mainPanelLayout.createSequentialGroup()
                .addContainerGap()
                .add(mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
                    .add(assesmentPanel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 444, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                    .add(jScrollPane1)
                    .add(questionLabel)
                    .add(jLabel1)
                    .add(org.jdesktop.layout.GroupLayout.TRAILING, mainPanelLayout.createSequentialGroup()
                        .add(0, 0, Short.MAX_VALUE)
                        .add(saveButton)))
                .addContainerGap())
        );
        mainPanelLayout.setVerticalGroup(
            mainPanelLayout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(mainPanelLayout.createSequentialGroup()
                .add(questionLabel)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jScrollPane1, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 55, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(jLabel1)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(assesmentPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED)
                .add(saveButton)
                .addContainerGap())
        );

        org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(mainPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING)
            .add(mainPanel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
    }// </editor-fold>//GEN-END:initComponents

    private void saveButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveButtonActionPerformed
        // TODO add your handling code here:
        try {
            delegate.saveButtonDidTap(evt, question);
        } catch (Exception e) {
            System.err.print("Error : Method was not found. " + e.getMessage());
        }
    }//GEN-LAST:event_saveButtonActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel assesmentPanel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JEditorPane questionEditorPanel;
    private javax.swing.JLabel questionLabel;
    private javax.swing.JButton saveButton;
    // End of variables declaration//GEN-END:variables

    private String[] studentAnswer;
    
    private MarkAnswerFormController delegate;

    private Question question;
}
